﻿using blackhouse.Locations;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace blackhouse.WebNemo.Business.DataTypes {
    public class LocationDataType : INemoDataType {

        public object ConvertFromDatabase(object adoObject) {
            if (adoObject is System.DBNull) return null;
            Location location = new Location();
            string adoValue = Convert.ToString(adoObject);
            if (String.IsNullOrEmpty(adoValue)) return location;
            string[] parts = adoValue.Split(';');
            if (parts.Length != 2) return location;
            double lat, lng;
            if (
                Double.TryParse(parts[0], System.Globalization.NumberStyles.AllowDecimalPoint, CultureInfo.GetCultureInfo("en-US"), out lat)
                && Double.TryParse(parts[1], System.Globalization.NumberStyles.AllowDecimalPoint, CultureInfo.GetCultureInfo("en-US"), out lng)
                ) {
                location.Latitude = lat;
                location.Longitude = lng;
            }
            return location;
        }

        public object ConvertToDatabase(object typeObject) {
            if (typeObject == null || typeObject is System.DBNull) return System.DBNull.Value;
            Location location = typeObject as Location;
            if (location == null) return System.DBNull.Value;
            return String.Format(CultureInfo.GetCultureInfo("en-US"), "{0};{1}", location.Latitude, location.Longitude);
        }
    }
}
